package com.kaiwukj.android.ufamily.mvp.ui.page.account;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.kaiwukj.android.mcas.mvp.BasePresenter;
import com.kaiwukj.android.mcas.utils.RxLifecycleUtils;
import com.kaiwukj.android.ufamily.app.MyApplication;
import com.kaiwukj.android.ufamily.app.constant.SPParam;
import com.kaiwukj.android.ufamily.hx.DemoHelper;
import com.kaiwukj.android.ufamily.hx.UserCacheManager;
import com.kaiwukj.android.ufamily.mvp.helper.TokenStore;
import com.kaiwukj.android.ufamily.mvp.http.api.ApiRespCode;
import com.kaiwukj.android.ufamily.mvp.http.callback.ApiCallBack;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.LoginResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.http.exception.ApiException;
import com.kaiwukj.android.ufamily.mvp.http.utils.RxUtils;
import com.kaiwukj.android.ufamily.utils.AESEncrypt;
import com.kaiwukj.android.ufamily.utils.SPUtils;
import com.zghl.mclient.client.ZghlMClient;
import com.zghl.mclient.client.ZghlStateListener;

import javax.inject.Inject;

import timber.log.Timber;

public class AccountPresenter extends BasePresenter<AccountContract.Model, AccountContract.View> {

    public static final int LOGIN = 1;//登录
    public static final int VERIFY_CODE_SEND = 2;//发送验证码
    public static final int VERIFY_CODE_CHECK = 3;//校验验证码
    public static final int PASS_UPDATE = 4;//更新密码


    @Inject
    public AccountPresenter(AccountContract.View view) {
        super(view);
    }

    public void loginByPass(String username, String password) {
        mModel.loginByPass(username, AESEncrypt.encrypt(password))
                .doOnSubscribe(act -> {
                    TokenStore.clear();
                    mRootView.showLoading("正在登录...");
                })
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<LoginResult>(mRootView) {
                    @Override
                    public void onSuccess(@NonNull LoginResult result) {
                        TokenStore.setToken(result.getAccess_token(), result.getToken_type());
                        //mRootView.loginSuccess();
                        getUserInfo();
                    }
                });
    }

    public void loginByCode(String mobile, String code) {
        mModel.loginByCode(mobile, code)
                .doOnSubscribe(act -> {
                    mRootView.showLoading("正在验证...");
                    TokenStore.clear();
                }).compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<LoginResult>(mRootView) {
                    @Override
                    public void onSuccess(@NonNull LoginResult result) {
                        TokenStore.setToken(result.getAccess_token(), result.getToken_type());
                        //  mRootView.loginSuccess();
                        getUserInfo();
                    }
                });
    }

    public void loginByWechat(String openId, String mobile, String code) {
        mModel.loginByWechat(openId, mobile, code)
                .doOnSubscribe(act -> {
                    mRootView.showLoading("正在登录...");
                    TokenStore.clear();
                })
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<LoginResult>(mRootView) {
                    @Override
                    public void onSuccess(@NonNull LoginResult result) {
                        TokenStore.setToken(result.getAccess_token(), result.getToken_type());
                        //mRootView.loginSuccess();
                        getUserInfo();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (e instanceof ApiException) {
                            ApiException ex = (ApiException) e;
                            if (ex.getErrCode() == ApiRespCode.ACCOUNT_UNBIND) {
                                mRootView.wechatBindMobild(openId);
                                return;
                            }
                        }
                    }
                });
    }

    public void loginByFast(String token, String opToken, String operator) {
        mModel.loginByFast(token, opToken, operator)
                .doOnSubscribe(act -> {
                    TokenStore.clear();
                    mRootView.showLoading("正在验证...");
                }).compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<LoginResult>() {
                    @Override
                    public void onSuccess(@NonNull LoginResult result) {
                        TokenStore.setToken(result.getAccess_token(), result.getToken_type());
                        //mRootView.loginSuccess();
                        getUserInfo();
                    }
                });
    }

    public void sendVerifyCode(String mobile) {
        mModel.sendVerifyCode(mobile)
                .doOnSubscribe(act -> {
                    TokenStore.clear();
                    mRootView.showLoading("正在发送...");
                })
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<Integer>(mRootView, VERIFY_CODE_SEND) {
                    @Override
                    public void onSuccess(@NonNull Integer result) {
                        LogUtils.d("验证码发送成功!!!");
                    }
                });
    }

    public void getUserInfo() {
        mModel.getUserInfo()
                .doOnSubscribe(act -> mRootView.showLoading("正在获取信息..."))
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<UserResult>(mRootView) {
                    @Override
                    public void onSuccess(@NonNull UserResult result) {
                        mRootView.hideLoading();
                        MyApplication.getInstance().setUserInfo(result);
                        ZghlMClient.getInstance().login(result.getPhone(), new ZghlStateListener() {
                            @Override
                            public void onSuccess(int i, String s) {
                                LogUtils.i("zghl login success:" + i + "-" + s);
                            }

                            @Override
                            public void onError(int i, String s) {
                                LogUtils.e("zghl login error:" + i + "-" + s);
                            }
                        });
                        loginHX(result);
                        mRootView.loginSuccess();
                    }
                });
    }

    public void updatePass(String newPass) {
        String rltPass = EncodeUtils.urlEncode(AESEncrypt.encrypt(newPass), "utf-8");
        mModel.updatePass(rltPass)
                .doOnSubscribe(act -> mRootView.showLoading("正在更新"))
                .compose(RxUtils.schedulerHelper())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ApiCallBack<Integer>(mRootView, PASS_UPDATE) {
                    @Override
                    public void onSuccess(@NonNull Integer result) {
                        LogUtils.d("密码修改成功");
                    }
                });
    }

    private void loginHX(UserResult result) {
        /*if (EMClient.getInstance().isLoggedInBefore) {
            LogUtils.i("已登录聊天服务器")
            return
        }*/
        if (result == null || result.getHxName() == null) return;
        EMClient.getInstance().login(result.getHxName().toLowerCase(), "jyl2020", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Timber.e("登录聊天服务器成功！");
                SPUtils.getInstance().put(SPParam.HX_USER_ID, result.getHxName().toLowerCase());
                SPUtils.getInstance().put(SPParam.HX_USER_NICK_NAME, result.getNickName());
                SPUtils.getInstance().put(SPParam.HX_HEAD_IMAGE, result.getHeadImg());
                LogUtils.e("--------------登录聊天服务器成功-----------");
                updateHxUser(result);
            }

            @Override
            public void onError(int code, String error) {
                LogUtils.e("--------------登录聊天服务器失败-----------" + code + ":" + error);
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });

    }

    private void updateHxUser(UserResult result) {
        try {
            UserCacheManager.save(result.getId(), result.getHxName().toLowerCase(), result.getNickName(), result.getHeadImg());
            DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(result.getNickName());
            DemoHelper.getInstance().getUserProfileManager().setCurrentUserAvatar(result.getHeadImg());
            DemoHelper.getInstance().setCurrentUserName(result.getHxName().toLowerCase()); // 环
        } catch (Exception e) {
            LogUtils.e("聊天用户信息更新失败");
        }
    }

}
